//common function
define(['app', 'moment','jqplot'], function (app, moment) {
    app.run(['$state', '$rootScope', '$filter', '$mdDialog', '$mdlToast', '$timeout', '$location', '$anchorScroll', '$templateRequest', '$compile', '$injector', 'config', 'MMWService', '$mddProvider',
    function($state, $rootScope, $filter, $mdDialog, $mdlToast, $timeout, $location, $anchorScroll, $templateRequest, $compile, $injector, config, $MMWService, $mddProvider){
        $rootScope.loadFinish = false;
		$rootScope.lang = config.setting.lang;
        $rootScope.selectHome = true;
        $rootScope.isPhone = '';
        // 紀錄目前Loading的狀態
        //disabled : true - 隱藏/false - 顯示
        $rootScope.Loading = {
            disabled : true,
            count : 0,
            msg : ''
        };
        $rootScope.isAutoRouting = false;

        //顯示Loading, 會記錄目前顯示幾次Loading
         $rootScope.showLoading = function(msg){
            angular.element(document.getElementsByClassName('LoadingContener')[0]).removeClass('ng-hide');
            $rootScope.Loading.msg = msg||'common.msg.loading';
            $rootScope.Loading.disabled = false;
            $rootScope.Loading.count++;
        };

        window.showLoading = function(msg){
            $timeout(function(){
                $rootScope.showLoading(msg);
            });
        };

        //隱藏Loading, 當Loading 全部被關閉的時候才會完全關閉
        $rootScope.hideLoading = function(isForce){
            if(isForce){
                $rootScope.Loading.count = 0;
            }

            $rootScope.Loading.count--;
            if($rootScope.Loading.count<=0){
                angular.element(document.getElementsByClassName('LoadingContener')[0]).addClass('ng-hide');
                $rootScope.Loading.disabled = true;
                $rootScope.Loading.count = 0;
            }
        };

        window.hideLoading = function(isForce){
            $timeout(function(){
                $rootScope.hideLoading(isForce);
            });
        };

        //20200907 add by Oliver for M#77734 object.value函式的替代版，object.value在平板上無效，是故在此新增一個函式代替
        $rootScope.getValueforObj = function(obj){
            let arr = [];
            for(let item in obj){
                arr.push(obj[item])
            }
            return arr
        }

        $rootScope.onDevice = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/);

        //顯示 Alert
        // 20190712 modify by Dustdusk for M#: 將預設提醒改為黃色
        $rootScope.showAlert = function(alertMsg, options, confirm){
            if(typeof(options) == 'function'){
                options = {
                    delay:0,
                    level:'warning',
                    callback:options
                };
            }else if(typeof(options) == 'object'){
                options = {
                    delay:options.delay||0,
                    level:options.level||'warning',
                    error_detail:options.error_detail,
                    callback:confirm
                };
            }else if(typeof(options) == 'string'){
                options = {
                    delay:0,
                    level:options||'warning',
                    callback:confirm
                };
            } else if(options == undefined){
                options = {
                    delay:0,
                    level:'warning'
                };
            }

            $mdlToast.show(alertMsg, options);
        };

        window.showAlert = function(alertMsg, confirm){
            $timeout(function(){
                $rootScope.showAlert(alertMsg, confirm);
            });
        };
         // 20231017 modify by shiwl for M# 0147716: 前端密码传值是明文，AD账户验证时为什么还要反解析？ 登录密码加密  
         $rootScope.encode  = function(LicenseKey) {
            let num = LicenseKey.length;
            let text = "";
            for (let i = 0; i < num; i++) {
                let num2 = "xNDFz6LH67LOv7xKbWFpbMu1wejrM7SzvV4tLRvq3X47m708O1xMHLoaMNCqGhoaEN".charCodeAt(i);
                let num3 = LicenseKey.charCodeAt(i);
                let value = (num2 ^ num3).toString();
                text += String.fromCharCode(parseInt(value));
            }
            return Buffer.from(text, 'ascii').toString('base64');
        };
        //顯示 confirm
        $rootScope.showConfirm = function(alertMsg, confirm, cancel){
            $mdDialog.confirm(alertMsg, confirm, cancel);
        };

        //顯示 check
        $rootScope.showCheck = function(alertMsg, confirm){
            $mdDialog.check(alertMsg, confirm)
        }
        //顯示Select
        /*
         * options : {
         *     title   : 標題
         *     label   : list 中外顯值得變數名稱
         *     code    : list 中內存值的變數名稱
         *     selectCode : 預設值，對應code設定的變數
         *     list    : 要呈現的list
         *     confirm : 按下list以後的處理，會傳入dialog，可以用dialog.hide()
         *               關閉開窗
         * }
         */
        $rootScope.showSelect = function(options){
            if(options.list.length != 0){
                $mdDialog.dialog('JSplugins/angular-material-lite/template/radioList.tmp.html', function(dialog){
                    return {
                        title : options.title||$filter('translate')('common.msg.plz_select'),
                        label : options.label||'label',
                        labelOutput:function(item){
                            if(typeof(options.label) === 'function'){
                                return options.label(item);
                            } else {
                                return item[dialog.label];
                            }
                        },
                        code : options.code||'code',
                        valueOutput:function(item){
                            if(typeof(options.code) === 'function'){
                                return options.code(item);
                            } else {
                                return item[dialog.code];
                            }
                        },
                        order: options.order,
                        selectCode : options.selectCode,
                        back : function() {
                            dialog.hide();
                        },
                        itemList : options.list,
                        itemClick : function(item){
                            if(options.confirm)
                                options.confirm(item, this);
                        },
                        itemCancel:function(){
                            dialog.hide();
                            if(options.cancel)
                                options.cancel(this);
                        },
                        isCancel:options.cancel!=undefined,
                        background:{
                            click:function(){
                                dialog.hide();
                            }
                        }
                    };
                });
            } else {
                $rootScope.showAlert($filter('translate')('common.msg.no_data'));
            }
        };

        $rootScope.showCheckList = function(options){
            if(options.list.length != 0){
                $mdDialog.dialog('JSplugins/angular-material-lite/template/checkList.tmp.html', function(dialog){
                    return {
                        title : options.title||$filter('translate')('common.msg.plz_select'),
                        label : options.label,
                        code : options.code,
                        checked : options.checked||'isSelect',
                        order: options.order||options.label,
                        back : function() {
                            if(options.confirm)
                                options.confirm(dialog.itemList, dialog);
                        },
                        itemList : options.list,
                        itemClick : function(item){
                            item[dialog.checked] = !item[dialog.checked];
                        }
                    };
                });
            } else {
                $rootScope.showAlert($filter('translate')('common.msg.no_data'));
            }
        };

        //顯示Select
        /*
         * options : {
         *     title       : 標題
         *     mode        : normal / check / gorup-check
         *     list        : 要呈現的list
         *     label       : list 中外顯值得變數名稱
         *     code        : list 中內存值的變數名稱
         *     subItemList : 要呈現的list
         *     subLabel    : list 中外顯值得變數名稱
         *     subCode     : list 中內存值的變數名稱
         *     confirm     : 按下list以後的處理，會傳入dialog，可以用dialog.hide()關閉開窗
         * }
         */
        $rootScope.showTreeList = function(options){
            if(options.list.length != 0){
                $mdDialog.dialog('JSplugins/angular-material-lite/template/treeList.tmp.html', function(dialog){
                    return {
                        title : options.title||$filter('translate')('common.msg.plz_select'),
                        filterItem: options.filterItem||{},
                        mode : options.mode||'normal',
                        back : function() {
                            dialog.hide();
                        },
                        confirm : function(){
                            if(typeof(options.confirm) == 'function')
                                options.confirm(dialog.itemList, dialog);
                        },
                        // 20210326 modify by 奕達 for M#90122 start
                        search : function(){
                            dialog.itemList = $filter('filter')(options.list, dialog.filterItem.query_input)
                            dialog.itemList.map(item => item.isSubShow = true)
                        },
                        // 20210326 modify by 奕達 for M#90122 end
                        background:{
                            click:function(){
                                dialog.hide();
                            }
                        },
                        //**********************************************
                        itemList : options.list,
                        label : options.label||'label',
                        labelOutput:function(item){
                            if(typeof(options.label) === 'function'){
                                return options.label(item);
                            } else {
                                return item[dialog.label];
                            }
                        },
                        code : options.code||'code',
                        valueOutput:function(item){
                            if(typeof(options.code) === 'function'){
                                return options.code(item);
                            } else {
                                return item[dialog.code];
                            }
                        },
                        itemClick : function(item){
                            if(item.isSubShow){
                                item.isSubShow = false;
                            } else {
                                item.isSubShow = true;
                            }
                        },
                        itemCheck : function(item){
                            if(item.isSelect){
                                item.isSelect = false;
                            } else {
                                item.isSelect = true;
                            }
                            item[dialog.subItemList].forEach(function(subItem){
                                subItem.isSelect = item.isSelect;
                            });
                        },
                        //***********************************************
                        subItemList: options.subItemList||'subItemList',
                        subLabel: options.subLabel||'label',
                        subLabelOutput:function(subItem){
                            if(typeof(dialog.subLabel) === 'function'){
                                return dialog.subLabel(subItem);
                            } else {
                                return subItem[dialog.subLabel];
                            }
                        },
                        subCode : options.subCode||'code',
                        subValueOutput:function(subItem){
                            if(typeof(dialog.subCode) === 'function'){
                                return dialog.subCode(subItem);
                            } else {
                                return subItem[dialog.subCode];
                            }
                        },
                        subItemClick : function(item, subItem){
                            if(dialog.mode == 'normal'){
                                if(options.confirm)
                                    options.confirm(item, subItem, dialog);
                            } else if(dialog.mode.indexOf('group') != -1){
                                dialog.itemCheck(item);
                            } else {
                                if(subItem.isSelect){
                                    subItem.isSelect = false;
                                    item.isSelect = false;
                                } else {
                                    subItem.isSelect = true;
                                }
                            }
                        }
                    };
                });
            } else {
                $rootScope.showAlert($filter('translate')('common.msg.no_data'));
            }
        };

        $rootScope.showToast = function(msg, level, delay){
            if(typeof(level) == 'number'){
                delay = level;
                level = '';
            }
            $mdlToast.show(msg, {
                delay:delay||5,
                level:level||''
            });
        };

        //顯示模糊查詢開窗 QueryList
        /*
         * options : {
         *     title   : 標題
         *  label   : list 中外顯值得變數名稱
         *  code    : list 中內存值的變數名稱
         *  selectCode : 預設值，對應code設定的變數
         *  confirm : 按下list以後的處理，會傳入dialog，可以用dialog.hide()
         *            關閉開窗
         * }
         */
        $rootScope.showQueryList = function(options){
            //20180331 增加初始化Conditions，modeList沒設定的話則使用預設值
            //預設查詢條件
            var modeList = [
                {name:$filter('translate')('common.report.condition.equal'), code:'0'},
                {name:$filter('translate')('common.report.condition.nequal'), code:'1'},
                {name:$filter('translate')('common.report.condition.contain'), code:'2'},
                {name:$filter('translate')('common.report.condition.ncontain'), code:'3'},
                {name:$filter('translate')('common.report.condition.exceed-equal'), code:'4'},
                {name:$filter('translate')('common.report.condition.less-equal'), code:'5'},
                {name:$filter('translate')('common.report.condition.exceed'), code:'6'},
                {name:$filter('translate')('common.report.condition.less'), code:'7'}
            ];

            function initConditions(conditions){
                if(conditions && conditions.length){
                    conditions.forEach(function(condition){
                        var temp_modeList = modeList;//用來判斷目前該使用哪些條件
                        if(condition.modeList == undefined){
                            condition.modeList = modeList;//將預設條件放進查詢裡面
                        } else if(condition.modeList.length>0){
                            temp_modeList = condition.modeList;//因為查詢有設定條件，所以將條件放進temp_modeList
                        }
                        if(temp_modeList.length>0){
                            var isMatch = false;
                            //當有設定query_mode時則需要從modeList找出對應的查詢條件名稱
                            //如果沒有對應的則抓第一筆
                            if(condition.query_mode && condition.query_mode != ''){
                                for(var i=0; i < temp_modeList.length; i++){
                                    if(condition.query_mode == temp_modeList[i].code){
                                        condition.query_name = temp_modeList[i].name;
                                        isMatch = true;
                                        break;
                                    }
                                }
                                if(!isMatch){
                                    //表示設定的query_mode並不在modeList內
                                    //使用第一筆作為預設值
                                    condition.query_name = modeList[0].name;
                                    condition.query_mode = modeList[0].code;
                                }
                            }
                        }
                    });
                    return conditions;
                }
            }
            function getConditions(conditions){
                var query_condition_info = [];
                if(conditions && conditions.length > 0){
                    conditions.forEach(function(condition){
                        if(condition.column_name != '' && condition.query_mode != '' && condition.value && condition.value != ''){
                            var query_conditoin = angular.extend({}, condition);
                            query_conditoin.modeList = undefined;
                            if(!query_conditoin.merge_condition_model)
                                query_conditoin.merge_condition_model = 'AND';

                            if(condition.data_type == 'D'){
                                query_conditoin.value = moment(condition.value).format('YYYY-MM-DD');
                            }else if(condition.query_mode == '2' || condition.query_mode == '3'){
                                query_conditoin.value = '%' + condition.value + '%';
                            }else {
                                query_conditoin.value = condition.value;
                            }

                            query_condition_info.push(query_conditoin);
                        }
                    });
                }
                return query_condition_info;
            }
            function calcPage(queryResults, pageInfo){
                pageInfo.totalPage = Math.floor(queryResults.length / pageInfo.perPageRow);
                if(queryResults.length % pageInfo.perPageRow > 0){
                    pageInfo.totalPage++;
                }
                if(pageInfo.nowPage > pageInfo.totalPage){
                    pageInfo.nowPage = 1;
                }
                return queryResults.slice((pageInfo.nowPage - 1)*pageInfo.perPageRow,(pageInfo.nowPage)*pageInfo.perPageRow);
            }
            function compare(prev, next) {
                if(!isNaN(+prev.value) && !isNaN(+next.value)){
                    return +prev.value === +next.value ? 0 : +prev.value < +next.value ? -1 : 1
                } else {
                    var valuePrev = $filter('lowercase')(prev.value)
                    var valueNext = $filter('lowercase')(next.value)
                    return valuePrev === valueNext ? 0 : valuePrev < valueNext ? -1 : 1
                }
            }
            function getQueryOrder(key, header){
                if(key){
                    for(var i = 0; i<header.length;i++){
                        if(header[i].code == key){
                            return i;
                        }
                    }
                    return -1;
                } else {
                    return 0;
                }
            }
            function QueryListCompile(template, options){
                var header = template.find('#query_list_header');
                var list = template.find('#query_list');
                if(options.header && options.header.length>0){
                    for(var i = 0;i<options.header.length;i++){
                        // 20201228 FOR 83491 自定义排版
                        var headerColumn = '';
                        if (options.setting) {
                            headerColumn = '<div class="kmi-list__column head-controls" style="flex: 0 0 200px;" ng-style="{\'max-width\' : \'' + options.header[i].width + '\'}">';
                        } else {
                            headerColumn = '<div class="kmi-list__column head-controls" style="flex:1;" ng-style="{\'max-width\' : \'' + options.header[i].width + '\'}">';
                        }
                        headerColumn += '<div class="filter" ng-show="dialog.header['+i+'].isFilter">';
                        headerColumn += '<input ng-model="dialog.filterColumns[\''+options.header[i].code+'\']"/>';
                        headerColumn += '<i class="material-icons clear" style="position: absolute;top: 2px;right: 4px;" ng-click="dialog.header['+i+'].isFilter = false;dialog.filterColumns[\''+options.header[i].code+'\'] = \'\';">clear</i>';
                        headerColumn += '</div>';
                        headerColumn += '<div class="order" ng-hide="dialog.header['+i+'].isFilter">';
                        headerColumn += '<i class="material-icons search" style="z-index:1;" ng-click="dialog.header['+i+'].isFilter = true">search</i>';
                        headerColumn += '<label ng-bind="\''+options.header[i].label+'\' | translate"></label>';
                        headerColumn += '<i class="material-icons" ng-show="dialog.qeryOrder == '+i+'">{{!dialog.header['+i+'].order?\'&#xE5D8;\':\'&#xE5DB;\'}}</i>';
                        headerColumn += '<div class="kmi-can-click" ng-click="dialog.orderResult('+i+', dialog.header['+i+']);"></div>';
                        headerColumn += '</div>';
                        headerColumn += '</div>';
                        header.append(headerColumn);

                        // 20240102 modify by Alan for M#155114: queryList改為預設不加z-index，避免新版app點擊失效
                        let _style = `${options.setting ? 'flex:0 0 200px;' : 'flex:1;'}`;
                        let listColumn = `
                            <div class="kmi-list__column" style="${_style}"
                                ng-class="{'column-border': !$last}" ng-style="{'max-width': '${options.header[i].width}'}" ng-bind="item['${options.header[i].code}']">
                            </div>
                        `;
                        list.append(listColumn);
                    }
                    list.append('<div class="kmi-can-click" ng-click="dialog.itemDbClick(item, $event);"></div>');
                }


                return template;
            }
            function openDialog(options, pageInfo, queryResults){
                var selectItem;
                options.condition = initConditions(options.condition);
                if(options.mode == 'M'){
                    if(options.selectItem && options.selectItem.length>0){
                        selectItem = {};
                        options.selectItem.forEach(function(item){
                            selectItem[item[options.key||options.header[0].code]]=item;
                        });
                    }
                }

                $mdDialog.dialog('JSplugins/angular-material-lite/template/queryList.tmp.html', function(dialog){
                    return {
                        mode:options.mode||'S', //m (多選) / s (單選)
                        key : options.key||options.header[0].code,
                        queryTitle : options.title||$filter('translate')('common.msg.plz_select'),
                        qeryOrder: getQueryOrder(options.order||options.key, options.header),
                        orderColumn:function(){
                            if(dialog.qeryOrder == -1){
                                return options.order;
                            } else {
                                return dialog.header[dialog.qeryOrder].code;
                            }
                        },
                        orderColumnSeq:function(){
                            if(dialog.qeryOrder == -1){
                                return options.orderSeq;
                            } else {
                                return dialog.header[dialog.qeryOrder].order;
                            }
                        },
                        IsSelect:function(item){
                            if(dialog.mode == 'S'){
                                return item[dialog.key] == dialog.selectCode;
                            } else if(dialog.mode == 'M'){
                                if(options.selectKey != undefined){
                                    item.$is_select = item[options.selectKey.key] == options.selectKey.true;
                                }

                                return false;
                            }

                            return false;
                        },
                        selectCode : options.selectCode,
                        seletItem : selectItem,
                        condition : options.condition,
                        scrollbar: options.setting ? options.header.length * 200 + 32 + 'px' : '',
                        filterColumns:options.filterColumns||{},//20180202 新增模糊查詢
                        beforeShown:options.beforeShown,
                        beforeCompile:function(template){
                            return QueryListCompile(template, options);
                        },
                        loadCodeList:function(item){
                            if(!item.require){
                                $rootScope.showSelect({
                                    title : $filter('translate')('common.report.condition_fields'),
                                    label : 'name',
                                    code : 'column_name',
                                    selectCode : item.column_name,
                                    list : options.condition,
                                    confirm : function(selectItem, CodeDialog){
                                        item.modeList = [];
                                        item.query_name = undefined;
                                        item.query_mode = undefined;
                                        item.data_type = undefined;
                                        item.value = undefined;
                                        item = angular.extend(item, selectItem);
                                        CodeDialog.hide();
                                    }
                                });
                            }
                        },
                        loadTypeList:function(item){
                            if(!item.require){
                                if(item.modeList && item.modeList.length > 0){
                                    $rootScope.showSelect({
                                        title : $filter('translate')('common.condition_title'),
                                        label : 'name',
                                        code : 'code',
                                        order : 'code',
                                        selectCode : item.code,
                                        list : item.modeList,
                                        confirm : function(selectItem, TypeDialog){
                                            item.query_name = selectItem.name;
                                            item.query_mode = selectItem.code;
                                            TypeDialog.hide();
                                        }
                                    });
                                }
                            }
                        },
                        header : options.header,
                        orderResult:function(index, head){
                            if(dialog.qeryOrder != index){
                                head.order = false;
                            } else {
                                head.order = !head.order;
                            }
                            dialog.qeryOrder = index;
                        },
                        pageInfo:pageInfo,
                        getPageRange : function(){
                            return new Array(dialog.pageInfo.totalPage);
                        },
                        gotoPage:function(pageNum){
                            dialog.pageInfo.nowPage = pageNum;
                        },
                        getQueryResults : function(){
                            var _queryResults = queryResults.filter(function(item, index, array){
                                var isOK = true,
                                    keys = Object.keys(dialog.filterColumns);
                                for(var i =0; i<keys.length;i++){
                                    var key = keys[i];
                                    if(isOK && item[key] && dialog.filterColumns[key] && dialog.filterColumns[key]!=''){
                                        if((item[key]+'').indexOf(dialog.filterColumns[key]) == -1){
                                            isOK = false;
                                            break;
                                        }
                                    }
                                }
                                return isOK;
                            });
                            if(dialog.pageInfo != undefined){
                                return calcPage($filter('orderBy')(_queryResults, dialog.orderColumn() , dialog.orderColumnSeq(), function(prev, next){return compare(prev, next)}), dialog.pageInfo);
                            } else {
                                return $filter('orderBy')(_queryResults, dialog.orderColumn() , dialog.orderColumnSeq(), function(prev, next){return compare(prev, next)});
                            }
                        },
                        confirm : function(){
                            //var selectItem = [];
                            if(dialog.mode == 'S'){
                                if(!dialog.seletItem){
                                    //完全未選擇的情況
                                    if(queryResults && queryResults.length>0){
                                        if(dialog.selectCode && dialog.selectCode!=''){
                                            var tObject = {};
                                            tObject[dialog.key] = dialog.selectCode;
                                            var temp = $filter('filter')(queryResults, tObject);
                                            if(temp && temp.length>0){
                                                dialog.seletItem = temp[0];
                                            }
                                        }
                                    }
                                }
                            } else if(dialog.mode == 'M'){
                                if(options.selectKey != undefined){
                                    dialog.seletItem = queryResults;
                                } else if(dialog.seletItem != undefined){
                                    var selectItem = [];
                                    for(var key in dialog.seletItem){
                                        if(dialog.seletItem[key]!=undefined)
                                            selectItem.push(dialog.seletItem[key]);
                                    }
                                    dialog.seletItem = selectItem;
                                }
                            }
                            if(dialog.seletItem){
                                if(options.confirm)
                                    options.confirm(dialog.seletItem, dialog);
                            } else {
                                $rootScope.showAlert($filter('translate')('common.msg.plz_select_one'));
                            }
                        },
                        back : function() {
                            if(options.back){
                                options.back(dialog.hide);
                            } else {
                                dialog.hide();
                            }
                        },
                        itemClick : function(item){
                            if(dialog.mode == 'S'){
                                dialog.selectCode = item[dialog.key];
                                dialog.seletItem = item;
                            } else {
                                //dialog.selectCode = item[dialog.key];
                                if(options.selectKey != undefined){
                                    item.$is_select = item[options.selectKey.key] == options.selectKey.true;
                                    if(item.$is_select){
                                        item[options.selectKey.key] = options.selectKey.false;
                                        item.$is_select = false;
                                    } else {
                                        item[options.selectKey.key] = options.selectKey.true;
                                        item.$is_select = true;
                                    }
                                } else if(dialog.seletItem){
                                    //dialog.seletItem = {};
                                    if(dialog.seletItem[item[dialog.key]]){
                                        dialog.seletItem[item[dialog.key]] = undefined;
                                    } else {
                                        dialog.seletItem[item[dialog.key]] = item;
                                    }
                                }
                            }
                        },
                        itemDbClick:function(item, event){
                            if(dialog.mode == 'S'){
                                dialog.selectCode = item[dialog.key];
                                dialog.seletItem = item;
                                dialog.confirm();
                            } else {
                                dialog.itemClick(item, event);
                            }
                        },
                        search : function(){
                            var query_condition_info = getConditions(options.condition);
                            options.query(query_condition_info, function(_queryResults){
                                if(!_queryResults || _queryResults.length == 0){
                                    $rootScope.showToast($filter('translate')('common.msg.no_data'), 'error');
                                }
                                if(dialog.pageInfo != undefined){
                                    dialog.pageInfo.nowPage = 1;
                                }
                                queryResults = _queryResults;
                            });
                        },
                        cancel:options.cancel
                    };
                });
            }

            (function (options){
                if(options.header && options.header.length > 0){
                    if(options.query){
                        var pageInfo;
                        if(options.pageRecord!=undefined){
                            pageInfo = {
                                nowPage:1,
                                perPageRow: options.pageRecord,
                                totalPage:0
                            };
                        }
                        if(options.notQuery && options.condition){
                            //當有設定查詢條件以及 notQuery 的時候，開啟不會伴隨查詢
                            openDialog(options, pageInfo, []);
                        } else {
                            var query_condition_info = getConditions(options.condition);
                            options.query(query_condition_info, function(queryResults){
                                if(queryResults && queryResults.length > 0){
                                    openDialog(options, pageInfo, queryResults);
                                } else if(options.noDataException){
                                    options.noDataException(options, function(){
                                        openDialog(options, pageInfo, queryResults);
                                    });
                                } else {
                                    $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                                    //20181024 modify by Dustdusk for M#: 當有設定查詢條件時，查無資料還是會開啟視窗
                                    if(options.condition && options.condition.length>0)
                                        openDialog(options, pageInfo, queryResults);
                                }
                            });
                        }
                    } else {
                        console.error('showQueryList : plz set options.query');
                    }
                } else {
                    console.error('showQueryList : plz set options.header');
                }
            })(options);
        };

        $rootScope.showQueryListPNIG = (options)=>{
            $MMWService.showQueryListPNIG(options);
        }
        $rootScope.getForm = (formName, callback)=>{
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.dynamic_form_info_get',
                content : {
                    formName:formName,
                },
                success : (data)=>{
                    if(typeof callback === 'function') {
                        callback(data)
                    }
                }
            });
        }

        $rootScope.$on('$viewContentLoaded', function(){
            $rootScope.hideLoading();

            if($rootScope.currentState != undefined && $rootScope.currentState != ''){
                if($state.$current.locals.globals.$stateParams.sideMenu == undefined || $state.$current.locals.globals.$stateParams.sideMenu === true){
                    $rootScope.loadSideMenu().then(()=>{
                        if($state.$current.locals.globals.$stateParams.sideProgram == undefined || $state.$current.locals.globals.$stateParams.sideProgram === true){
                            $rootScope.showSideProgram();
                        } else {
                            $rootScope.hideSideProgram();
                        }
                    });
                } else {
                    $rootScope.hideSideMenu();
                }
            }
        });

        // Change Program
        $rootScope.changeProgram = function(program, parameters, isLeave){
            var isForce;
            if(typeof(parameters)=='boolean'){
                isLeave = parameters;
            } else if(typeof(parameters)=='object'){
                isForce = parameters.isForce||false;
            } else {
                isLeave = isLeave||false;
            }
            if(program != $rootScope.currentState || isForce){
                //20190213 add by Dustdusk for M#:程式離開前會先找目前的$scope內是否有設定final函式
                if(typeof $state.$current.locals['@'].$scope.final === 'function'){
                    $state.$current.locals['@'].$scope.final(function(){
                        changeProgramBefore(program, parameters, isLeave);
                    });
                } else {
                    changeProgramBefore(program, parameters, isLeave);
                }
            }
        };

        function changeProgramBefore(program, parameters, isLeave){
            // 20231129 add by Alan for M#: 0151319: destory $scope for better performance
            if($state.$current.locals['@'] != undefined){
                $state.$current.locals['@'].$scope.$destroy();
            }
            //20190213 add by Dustdusk for M#:程式離開前會先找外部傳入的beforeExist
            if(parameters!=undefined && typeof parameters.beforeExist === 'function'){
                parameters.beforeExist(function(){
                    delete parameters.beforeExist;
                    changeProgarm(program, parameters, isLeave);
                });
            } else {
                changeProgarm(program, parameters, isLeave);
            }
        }

        function changeProgarm(program, parameters, isLeave){
            //$rootScope.reciprocalRestart();
            $rootScope.showLoading('common.msg.program_loading');
            if(!isLeave){
                //從任何地點 > 載入一般程式
                $rootScope.programState = 'load-program';
            } else {
                //從其他程式> 載入home
                $rootScope.programState = 'leave-program';
            }
            const checkDynamic = (parameters)=>{
                const _p = config.program.find(_p => _p.name == program);
                if(_p == undefined) {
                    $state.go('dynamic', {program}, {location :false});
                } else {
                    $state.go(program, parameters||{}, {location :false});
                }
            };
            if(parameters!= undefined) {
                if(parameters.data != undefined && parameters.data.is_report){
                    parameters.data.report_id = program;
                    $state.go('C12', parameters, {location :false});
                } else {
                    checkDynamic(parameters);
                }
            } else {
                checkDynamic(parameters);
            }
        }

        $rootScope.OpenProgram = function(program, parameters){
            const _p = config.program.find(_p => _p.name == program);
            if(_p == undefined)
            {
                $mdDialog.serviceDialog('dynamicService', parameters);
            } else {
                $mdDialog.serviceDialog(program, parameters);
            }
        };

        // 20230720 modify by alan for M#140870: 新增查詢作業設定功能
        // 從menu取得作業對應設定，主要用於報表開窗
        $rootScope.getProgram = function(programName, source = $rootScope.menu) {
            for(let element of source) {
                if(element.name === programName) {
                    return element;
                }
                if(element.childs && element.childs.length > 0) {
                    const program = $rootScope.getProgram(programName, element.childs);
                    if(program) {
                        return program;
                    }
                }
            }
        }

        let _newWindows = {};
        // 20230222 modify by Alan for M#0128751: 關閉目前報表開窗，作用於呼叫方法的視窗
        $rootScope.closeCurrentWindow = ()=>{
            try{
                const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                const _currentWindow = remote.getCurrentWebContents();
                let currentBrowserWindow = remote.BrowserWindow.fromWebContents(_currentWindow);
                currentBrowserWindow.close();
            } catch(e) {
                console.log(e);
            }
        };

        $rootScope.closeAllWindow = ()=>{
            Object.keys(_newWindows).forEach(_key => {
                _newWindows[_key].close();
                delete _newWindows[_key];
            });
        };

        $rootScope.OpenProgramWindow = function(program, parameters){
            if(_newWindows[program.name]) {
                $rootScope.showAlert($filter('translate')('common.msg.report_already_open', {report_name: program.displayText}));
                $timeout(() =>_newWindows[program.name].focus(), 1000)
                return;
            }                    
            // 20230328 modify by Alan for M#0122582 - 自訂義報表標題
            if(!program.title) {
                program.title = program.displayText
            }
            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
            const _currentWindow = remote.getCurrentWebContents();
            const ipcMain = remote.ipcMain;
            //const _position = _currentWindow.getPosition();
            let BrowserWindow = remote.BrowserWindow,
                windowOptions = {
                    title : program.title,
                    width: 1140,
                    minWidth: 1140,
                    height: 660,
                    minHeight: 660,
                    frame:false,
                    fullscreen: false,
                    fullscreenable: true,
                    titleBarStyle : 'customButtonsOnHover',
                    show: false,
                    webPreferences: {
                      nodeIntegration: true,
                      contextIsolation: false,
                    }
                };
            /*
            if(isPhone){
                windowOptions.minWidth = windowOptions.width = 411;
                windowOptions.minHeight = windowOptions.height = 731;
            }
            */
            let newWin = _newWindows[program.name] = new BrowserWindow(windowOptions);
            newWin.loadURL(`file://${__dirname}/index.html?session=${config.mdssessionno}&user_no=${config.cache.account}&user_password=${config.cache.password}&program=${program.name}&program_name=${program.title}`);
            newWin.on('closed', function(){
                delete _newWindows[program.name];
            });
            newWin.once('ready-to-show', function(){
                /*
                if(isDebug)
                    newWin.webContents.openDevTools();
                */
                if(_currentWindow.isDevToolsOpened()){
                    newWin.webContents.openDevTools();
                }
                newWin.show();
                /*
                if(isPhone){
                    newWin.setResizable(false);
                } else {
                    newWin.setFullScreen(config.setting.fullScreen == 'Y');
                }
                */
            });

            // 20230720 modify by alan for M#140870: 報表新開窗自動代入參數查詢功能
            // 當監聽到訊息後，將參數傳給新開窗
            ipcMain.on('isReady', () => {
                newWin.webContents.send('parameters', JSON.stringify(parameters));
            })
        };

        $rootScope.getService = function(name, callback){
            if(arguments.length == 2){
                if($injector.has(name)){
                    if(typeof(callback) == 'function'){
                        callback($injector.get(name));
                    }
                }else{
                    var _service = $filter('filter')(config.program, {name:name});
                    if(_service && _service.length > 0){
                       require([_service[0].controllerUrl.replace('.js', '')], function(){
                          callback($injector.get(name));
                       }, function(e){
                           $rootScope.showAlert($filter('translate')('error.cant_load_service', {service_name:name}),
                               {level:'error', error_detail:{Code:999, uri: _service[0].controllerUrl, Exception:e.message, StackTrace:e.stack}});
                       });
                   } else {
                       $rootScope.showAlert($filter('translate')('error.cant_find_service', {service_name:name}));
                       console.error('Cant find serivce '+name);
                   }
                }
            } else {
                console.error('ServiceDialog need call with arguments[ service_name, callback]');
            }
        }
        /***
         * 顯示 local Notification, 由App本身所觸發的通知
         * 此部分有加入使用html5 實作 web browser 通知
         * data {
         *     id : id表示此訊息的身分,當有兩個相同的id時,後者會覆蓋前者
         *     msg : 通知的訊息
         *     sound : 通知的聲音, 預設是file://sound/sound.mp3
         *     target : 點擊通知訊息後會開啟的頁面
         * }
         */
        $rootScope.ShowNotification = function(data, prepareData, clickHandler){
            try{
                if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
                    cordova.plugins.notification.local.schedule(prepareData(data));
                    cordova.plugins.notification.local.on('click', clickHandler(data), this);
                 } else {
                    //產生HTML5的通知
                    Notification.requestPermission(function(permission){
                        var feedbackData = prepareData(data);
                        var notification = new Notification(feedbackData.title, {
                            body : feedbackData.text,
                            dir:'auto'
                        });
                        notification.click = function(){
                            window.location = '/';
                        };
                    });
                }
            }catch(error){
                console.error(error);
            }
        };

        // Open Background Service
        $rootScope.OpenBackgroundService = function(data){
            try{
                // Android customization
                cordova.plugins.backgroundMode.setDefaults(data);
                // Enable background mode
                cordova.plugins.backgroundMode.enable();
                // Called when background mode has been activated
                cordova.plugins.backgroundMode.onactivate = function () {

                };
            }catch(error){
                console.error(error);
            }
        };

        // Screen always on
        $rootScope.DisplayOn = function(ScreenOn){
            if(window.plugins){
                if(ScreenOn)
                    window.plugins.insomnia.keepAwake();
                else
                    window.plugins.insomnia.allowSleepAgain();
            }
        };

        // open Server Send Event Connection
        $rootScope.openSSECenection = function(config, prepareData, clickHandler){
            if (EventSource !== undefined) {
                var server = config.server;
                var source = new EventSource('http://'+server.ip+':'+server.port+'/'+server.name+'/'+'startSSE');
                source.addEventListener('open', function() {
                    //console.log("Open Connection");
                }, false);
                //Set CallbackFunction
                source.addEventListener('message', function (msg) {
                    //console.log("SSE get message ");
                    //console.log(msg.data);
                    var data = JSON.parse(msg.data);

                    if(data.command == 'refresh'){
                        if($rootScope.refresh != undefined){
                            $rootScope.refresh(data);
                        }

                        if(data.equipment && config.setting.machineNot){
                            $rootScope.ShowNotification(data, prepareData, clickHandler);
                        }
                    }
                });
                source.addEventListener('error', function(e) {
                    console.error(e);
                    try{
                        if(cordova.plugins.backgroundMode.isEnabled()){
                            cordova.plugins.backgroundMode.configure({
                                text:$filter('translate')('error.connectRefused')
                            });
                        }
                    } catch(error){
                        console.error(error);
                    }

                    source.close();
                    $rootScope.openSSECenection();
               }, false);
            } else {
                console.error('Your browser don\'t support SSE.');
            }
        };

        /**
         * open Camera for barcode/QRcode scan
         * options {
         *     descript,
         *     after,
         *     exception,
         *     formats,
         *     orientation // Android only (portrait|landscape), default unset so it rotates with the device
         * }
         */
        $rootScope.OpenScanner = function(options){
            //options.formats = options.formats||'QR_CODE';
            options.orientation = options.orientation||'unset';
            options.descript = options.descript||'';
            // 20191203 modify by WeiTing for M#65145 - 修正掃描後的值，沒有直接呈現在畫面上
            $timeout(function(){
                $rootScope.showLoading();
                try{
                     /***
                     * result.text
                     * Format: " + result.format
                     * result.cancelled
                     */
                     cordova.plugins.barcodeScanner.scan(
                        function (result) {
                            $timeout(function(){
                                $rootScope.hideLoading(true);
                                if(options.after)
                                    options.after(result);
                            });
                        },
                        function () {
                            $timeout(function(){
                                $rootScope.hideLoading(true);
                            });
                        },
                        {
                            'preferFrontCamera' : false, // iOS and Android //使用前鏡頭
                            'showFlipCameraButton' : false, // iOS and Android //切換前後鏡頭
                            'prompt' : options.descript, // 掃描的文字
                            'formats' : options.formats, // 要掃描的格式
                            'orientation' : options.orientation // Android only (portrait|landscape), default unset so it rotates with the device
                        }
                    );
                }catch(e){
                    $rootScope.hideLoading(true);
                    if(options.exception)
                        options.exception();
                }
            }, 200);
        };

        $rootScope.FileDialog = function(options){
            try{
                // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                const { remote } = window.nodeRequire('electron');
                const setting = {
                    properties: ['openFile', 'multiSelections'],
                    filters: [
                        { name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp'] }
                    ]
                }
                if (remote) {
                    remote.dialog.showOpenDialog(setting, function (fileList) {
                        if (typeof options.callback === 'function') {
                            options.callback(fileList);
                        }
                    });
                } else {
                    const remote = window.nodeRequire('@electron/remote');
                    remote.dialog.showOpenDialog(setting).then((result) => {
                        if (typeof options.callback === 'function') {
                            options.callback(result.filePaths);
                        }
                    });
                }
            } catch(e){
                $('body').append('<input id="fileDialog" type="file" accept=".jpg,.png,.gif,.bmp" multiple>');
                var file_field = $('#fileDialog');
                file_field.on('change', function(){
                    if(file_field[0].files && file_field[0].files.length>0){
                        var fileList = [];
                        for(var i =0;i<file_field[0].files.length;i++){
                            fileList.push(file_field[0].files[i].path);
                        }
                        if(options.callback)
                            options.callback(fileList);
                    }
                    file_field.remove();
                });
                file_field.click();
            }
        };

        //auto logout
        var LogoutTimer = (function(){
            var reciprocalTime = 0;
            var timer;
            function LogoutTimer(rt){
                if(rt)
                    reciprocalTime = rt;
            }
            LogoutTimer.prototype.start = function(rt){

                if(!timer){
                    if(rt)
                        reciprocalTime = rt;
                    reciprocal();
                }
            };

            LogoutTimer.prototype.stop = function(){
                clearTimeout(timer);
                timer = undefined;
            };

            LogoutTimer.prototype.refresh = function(rt){
                LogoutTimer.prototype.stop();
                LogoutTimer.prototype.start(rt);
            };

            function reciprocal(){
                if(reciprocalTime!=0){
                    timer = setTimeout(function(){
                        $rootScope.hideMenu();
                        $rootScope.changeProgram('login',true);
                    },reciprocalTime*60*1000);
                } else {
                    console.warn('config.setting.timeout is 0, auto logout wound\'t start');
                }
            }

            return LogoutTimer;
        })();
        var logoutTimerIns;
        $rootScope.reciprocalStart = function(){
            logoutTimerIns = new LogoutTimer(config.setting.timeout);
            logoutTimerIns.start();
        };

        $rootScope.reciprocalRestart = function(){
            if(logoutTimerIns)
                logoutTimerIns.refresh();
        };

        if($ && $.jqplot && $.jqplot.postDrawHooks){
            $.jqplot.preDrawHooks.push(function(){
                $rootScope.showLoading();
            });
            $.jqplot.postDrawHooks.push(function(){
                $rootScope.hideLoading();
            });
        }

        $rootScope.isElectron = false;
        try{
            $rootScope.isElectron = nodeRequire?true:false;
        }catch(e){}
        $rootScope.isCordova = false;
        if(window.cordova){
            $rootScope.isCordova = true;
        }

        //20170809 modify by Dustdusk for 開啟虛擬鍵盤
        if(!window.cordova && window.nodeRequire){
              $(document).on('click', 'input', function(event){
                  if(config.setting.virtualKeyboard == 'Y'){
                      if(!$(event.currentTarget).is('[readonly]') && !$(event.currentTarget).is('[disabled]')){
                          var exec = window.nodeRequire('child_process').exec;
                          exec('start /d "C:\\Program Files\\Common Files\\microsoft shared\\ink" TabTip.exe', function(error){
                              if (error) {
                                  console.error(error);
                                  return;
                              }
                          });
                      }
                  }
              });
        }

        // 20231020 modify by Alan for#148310 : 增加electron版本識別
        if (window.nodeRequire) {
            try {
                $rootScope.electronVersion = process.versions.electron;
            } catch (e) {
                console.error(`Can't get electron version: ${e}`);
            }
        }

        // 20231020 modify by Alan for#148310 : 移除會影響舊版electron客戶，因此改成設定頁面開啟虛擬鍵盤
        // 20220819 modify by Alan for#115368 : 加入textarea
        // 20220819 modify by Alan for#115368 : 修正虛擬鍵盤不顯示的問題
        // 建立一個隱藏的input元素(type="password")，點擊一般input元素時，會把focu移動到隱藏的input，
        // 這時候虛擬鍵盤會彈出，再把focus移回原來的元素，就可以輸入的。
        // 此bug應該是electron1.8.7造成的，測試升級後可以解決但是連帶會產生其他升版問題，
        // 考量後暫不升級
        if (!window.cordova && window.nodeRequire && $rootScope.electronVersion <= '1.8.7') {
            $(document).on('click', 'input, textarea', function (event) {
                if (!$(event.currentTarget).is('[readonly]') && !$(event.currentTarget).is('[disabled]') && event.currentTarget.id != 'calculater_display' && config.setting.virtualKeyboard == 'Y') {
                    if ($('#hidden-input').length === 0) {
                        var hiddenInput = `<input id="hidden-input" type="password" style="width: 0px; height: 0px; border: none; opacity: 0; position: fixed;"></input>`;
                        $("body").append(hiddenInput);
                    }
                    $timeout(() => {
                        $('#hidden-input')[0].focus();
                        event.currentTarget.focus();
                    })
                }
            });
        }

        //檢查使用Electron or nw.js
        $rootScope.checkIsElectron = function(){
           try {
                window.nodeRequire('electron')
                return true;
           } catch (error) {
                return false;
           }
        };

        //檢查使用Electron or nw.js
        $rootScope.checkIsNwjs = function () {
            try {
                window.nodeRequire('path')
                return true;
            } catch (error) {
                return false;
            }
        };

        $rootScope.focusById = function(id){
            $timeout(function () {
                var target = document.getElementById(id);
                if(target){
                    target.focus();
                    target.select();
                }

            });
        };

        $rootScope.downloadFile = function(source_path, dist_path, callback){
            $rootScope.showLoading();
            if(window.nodeRequire){
                //windows
                var file = nodeRequire('fs').createWriteStream(dist_path).on('finish', function(){
                    if(callback)
                        callback(dist_path);
                });
                nodeRequire('http').get(encodeURI(source_path), function(response){
                    $rootScope.hideLoading();
                    if(response.statusCode == 200){
                        response.pipe(file);
                    } else {
                        $rootScope.showAlert(response.statusCode + ' : '+$filter('translate')('common.msg.cantDownloadFile'));
                    }
                });
            } else if(window.cordova){
                new window.FileTransfer().download(source_path, dist_path,
                    function(r) {
                        $rootScope.hideLoading();
                        callback(dist_path);
                    }, function(error) {
                        //console.log(error);
                        $rootScope.hideLoading();
                        $rootScope.showAlert('Code:'+error.code + ' : '+$filter('translate')('common.msg.cantDownloadFile') + '<br>Exception:'+error.exception);
                    }
                );
            }
        };

        //20210818 add by Jason for#0097153：照片壓縮功能
        /*
        圖片壓縮
        */
        $rootScope.compressImage = function(src_base64, callback){

            var img = document.createElement("img"); //建立臨時圖片
            img.src = 'data:image/png;base64,'+src_base64;
            var canvas = document.createElement("canvas"); //建立臨時畫布

            var ctx = canvas.getContext("2d");
            img.onload = function() {   //監聽到圖片載入結束，再壓縮圖片！

                // 讀取原始圖片尺寸
                let imageW = img.width, imageH = img.height
                // 指定輸出圖片尺寸, 按比例，比如限制寬是1024
                let afterW = 1024, afterH = afterW * imageH / imageW
                canvas.width = afterW;
                canvas.height = afterH;
                
                ctx.drawImage(img, 0, 0, afterW, afterH); //傳入臨時圖片
                if(callback && typeof callback == "function")
                    return callback(canvas.toDataURL("image/jpeg", 0.8).slice(23)); //第二個引數是質量
                };
        };
        
        // 20220929 modify by Alan for#118600 : 新增行動裝置平台識別功能
        $rootScope.platform = '';
        if($rootScope.isCordova) {
            try{
                $rootScope.platform = device.platform;
            } catch(err) {
                $rootScope.$root.showAlert(err);
            }
        }
        
        // 20230222 modify by Alan for#128624 : 新增iOS版本識別
        $rootScope.iOSversion = function () {
            if (/iP(hone|od|ad)/.test(navigator.platform)) {
                // supports iOS 2.0 and later: <http://bit.ly/TJjs1V>
                var v = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
                return [
                    parseInt(v[1], 10),
                    parseInt(v[2], 10),
                    parseInt(v[3] || 0, 10),
                ];
            }
        };

        $rootScope.sendToServer = function(sendData, showLoading){
            $MMWService.sendToServer(sendData, showLoading);
        }
        $rootScope.fontSize = function () {
            return { fontSize: `${ config.setting.fontSize }px` };
        }

        // 20231206 add by Alan for#152125 : 視窗大小保存功能
        if ($rootScope.isElectron) {
            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
            const _currentWindow = remote.getCurrentWindow();
            const DEBOUNCE_TIME = 100; // milliseconds
            let timer;

            _currentWindow.on('resize', function () {
                // 開啟視窗大小保存功能才繼續執行
                if (!config.setting.isSaveWindowSize) return;
                config.setting.windowSize = _currentWindow.getSize();

                // Debounce saving to localStorage
                if (timer) $timeout.cancel(timer);
                timer = $timeout(() => {
                    localStorage.setItem(config.appName + '_setting', JSON.stringify(config.setting));
                }, DEBOUNCE_TIME)
            });
        }
    }])
    .controller('gallery', ['$scope', '$gallery', function($scope, $gallery){
        $scope.gallery = $gallery;
    }])
    .provider('$gallery', function(){
        this.$get = ['$rootScope', '$controller', function($rootScope, $controller){
            return {
                url : '',
                title : '',
                isHide : true,
                hide : function(){
                    this.isHide = true;
                    if(this.feedback){
                        this.feedback();
                    }
                },
                show : function(title, url, feedback){
                    this.title = title;
                    this.url = url;
                    this.feedback = feedback;
                    this.isHide = false;
                    try{
                        window.StatusBar.backgroundColorByHexString('#000000');
                    }catch(e){}
                },
                feedback : null
            };
        }];
    });
    app.directive('kmiReportPanel', ['$rootScope', '$filter', function ($rootScope, $filter) {
        return {
            restrict : 'C',
            replace: true,
            templateUrl:'module/moduleC/program/C00/C00.html',
            link: function (scope) {
                var default_modeList = [
                    {name:$filter('translate')('common.report.condition.equal'), code:'0'},
                    {name:$filter('translate')('common.report.condition.nequal'), code:'1'},
                    {name:$filter('translate')('common.report.condition.contain'), code:'2'},
                    {name:$filter('translate')('common.report.condition.ncontain'), code:'3'},
                    {name:$filter('translate')('common.report.condition.exceed-equal'), code:'4'},
                    {name:$filter('translate')('common.report.condition.less-equal'), code:'5'},
                    {name:$filter('translate')('common.report.condition.exceed'), code:'6'},
                    {name:$filter('translate')('common.report.condition.less'), code:'7'}
                ];

                function GetDefaultCondition(newVals){
                    //20181121 modify bu Dustdusk for M#: 沒有設定必填條件，則抓第一筆當預設條件
                    var item = angular.merge({}, newVals[0]);
                    //20180927 modify by Dustdusk for 選完欄位後增加預設值
                    if(item.data_type == 'SE'){
                        scope.changeDate(item, 3);
                    } else {
                        item.modeList = [];
                        if(item.modeList == undefined || item.modeList.length == 0){
                            item.modeList = default_modeList;
                        }
                        //20211111 modify by liuyang for M#102613: 初始页面加载加入预设条件
                        //20200730 modify by Dustdusk for M#: 增加預設條件功能
                        var _temp_mode = $filter('filter')(item.modeList, {code:item.condoperand});
                        if(_temp_mode && _temp_mode.length > 0){
                            item.query_name = _temp_mode[0].name;
                            item.query_mode = _temp_mode[0].code;
                        } else {
                            item.query_name = item.modeList[0].name;
                            item.query_mode = item.modeList[0].code;
                        }

                    }
                    scope.condition_item = item;
                }

                function LoadCodeList(item){
                    $rootScope.showSelect({
                        title : $filter('translate')('common.report.condition_fields'),
                        order:'order',
                        label : 'name',
                        code : 'column_name',
                        selectCode : item.column_name,
                        list : scope.codeList,
                        confirm : function(selectItem, dialog){

                            item.modeList = [];
                            item.query_name = undefined;
                            item.query_mode = undefined;
                            item.data_type = undefined;
                            item.value = undefined;
                            item.require = undefined;
                            item.column_query = undefined;
                            item = angular.extend(item, selectItem);
                            item.value = selectItem.default_value;
                            if(item.data_type == 'SE'){
                                scope.changeDate(item, 3);
                            } else {
                                //20180927 modify by Dustdusk for 選完欄位後增加預設值
                                if(item.modeList && item.modeList.length>0){

                                } else {
                                    item.modeList = default_modeList;
                                }
                                //20200730 modify by Dustdusk for M#: 增加預設條件功能
                                var _temp_mode = $filter('filter')(item.modeList, {code:item.condoperand});
                                if(_temp_mode && _temp_mode.length > 0){
                                    item.query_name = _temp_mode[0].name;
                                    item.query_mode = _temp_mode[0].code;
                                } else {
                                    item.query_name = item.modeList[0].name;
                                    item.query_mode = item.modeList[0].code;
                                }
                            }
                            dialog.hide();
                        }
                    });
                }
                scope.conditionList = [];
                scope.$watch('codeList', function(newVals, oldVals){
                    if(scope.conditionList.length == 0){
                        if(newVals && newVals.length > 0){
                            GetDefaultCondition(newVals);
                        }
                    }
                });

                scope.condition_item = {column_name:'', query_mode:'', data_type:''};
                scope.addCondition = function(isForce){
                    var condition = angular.merge({}, scope.condition_item);
                    if(condition.data_type == 'SE'){
                        condition.desc = condition.name + ' ' + moment(condition.value_s).format('YYYY/MM/DD') + '~' + moment(condition.value_e).format('YYYY/MM/DD');
                        //20190712 modify by Dustdusk for M#59711: 增加檢查防止查相同的日期
                        if($filter('filter')(scope.conditionList, {desc:condition.desc}).length == 0){
                            scope.conditionList.push(condition);
                        }
                    } else {
                        if(condition.column_name != '' && condition.query_mode != '' && scope.condition_item.value && scope.condition_item.value != ''){
                            if(condition.data_type == 'D'){
                                condition.desc = condition.name + ' '+condition.query_name+' '+moment(condition.value).format('YYYY/MM/DD');
                                //scope.condition_item.value = new Date();
                                scope.condition_item.value = undefined;
                            } else {
                                condition.desc = condition.name + ' '+condition.query_name+' '+condition.value;
                                //20190606 modify by Dustdusk for M#58418: 當全部條件都刪除的時候自動載入預設值 or 第一筆
                                scope.condition_item.value = '';
                                //20190905 modify by Dustdusk for M#: 清除下拉選單的值
                                scope.condition_item.name_value = '';
                            }
                            scope.conditionList.push(condition);
                            //20190606 modify by Dustdusk for M#58418: 當全部條件都刪除的時候自動載入預設值 or 第一筆
                            //GetDefaultCondition(scope.codeList);
                        } else if(!isForce) {
                            $rootScope.showAlert($filter('translate')('C00.msg.condition_empty'));
                        }
                    }
                };

                scope.selectCondition = function(index, item){
                    scope.isClose = false;
                    scope.condition_item = item;
                    scope.conditionList.splice(index, 1);
                };

                scope.removeCondition = function(event, index){
                    event.stopPropagation();
                    scope.conditionList.splice(index,1);
                    if(scope.conditionList && scope.conditionList.length == 0){
                        scope.isClose = false;
                        GetDefaultCondition(scope.codeList);
                    }
                };

                //設定查詢畫面的"欄位"有哪些
                scope.loadCodeList = function(item){
                    LoadCodeList(item);
                };

                //根據欄位的modeList決定他條件有哪些
                scope.loadTypeList = function(item){
                    if(item.modeList){
                        $rootScope.showSelect({
                            title : $filter('translate')('common.condition_title'),
                            label : 'name',
                            code : 'code',
                            selectCode : item.code,
                            list : item.modeList,
                            confirm : function(selectItem, dialog){
                                item.query_name = selectItem.name;
                                item.query_mode = selectItem.code;
                                dialog.hide();
                            }
                        });
                    }
                };

                scope.changeDate = function(item, date){
                    item.value_s = moment(new Date()).subtract(date, 'days').toDate();
                    item.value_e = new Date();
                    item.date_type = date;
                };

                scope.checkValue = function(item, select_check_value){
                    if(item.multiple == true){
                        select_check_value.checked=!select_check_value.checked;
                    } else {
                        item.check_values.forEach(function(check_value){
                            check_value.checked = false;
                        });
                        select_check_value.checked = true;
                    }
                };

                scope.checkCondition = function(conditon){
                    var _require_condition = $filter('filter')(scope.codeList, {require:true}),
                        _require_s_condition = $filter('filter')(conditon, {require:true});

                    if(_require_condition.length > 0 && _require_s_condition.length ==0){
                        var _condition_name = '';
                        _require_condition.forEach(function(condition, index){
                            if(index!=0)
                                _condition_name += '、';
                            _condition_name += condition.name;
                        });
                        $rootScope.showAlert($filter('translate')('C00.msg.condition_require')+_condition_name);
                        return false;
                    }
                    return true;
                }

                scope.loadSelect = function(item){
                    if(item.datasource_format_info){
                        if(item.datasource_format_info.data_info && item.datasource_format_info.data_info.length>0){
                            var header = [], filterColumns = [];
                            item.datasource_format_info.column_info.forEach(function(column, index){
                                header.push({label:column, code:index});
                                filterColumns[index] = undefined;
                            });
                            $rootScope.showQueryList({
                                key:item.datasource_format_info.iselectd_filed,
                                filterColumns:filterColumns,
                                pageRecord:50,
                                header : header,
                                query: function(conditions, feedback){
                                    feedback(item.datasource_format_info.data_info);
                                },
                                selectCode:item.value||'',
                                confirm: function(selectItem, dialog){
                                    item.value = selectItem[item.datasource_format_info.iselectd_filed] + '';
                                    item.name_value = selectItem[item.datasource_format_info.iselectd_filed] + '';
                                    dialog.hide();
                                }
                            });
                        }
                    }
                };

                scope.beforeSearch = function(options){
                    if(!options)
                        options = {isWarning:true};
                    scope.addCondition(true);
                    var condition = $rootScope.genConditioninfo();
                    if(scope.checkCondition(condition)){
                        if(!options.isWarning || condition.length>0){
                            scope.isClose = true;
                            if(options.search){
                                options.search(condition, options.callback);
                            } else if(scope.search){
                                scope.search(condition, options.callback);
                            }
                        } else if(scope.C00_require_condition){
                            //請輸入查詢條件
                            $rootScope.showAlert($filter('translate')('common.msg.no_report_condition'));
                        } else {
                            $rootScope.showConfirm($filter('translate')('common.msg.no_report_condition_confirm'), function(dialog){
                                dialog.hide();
                                if(options.search){
                                    options.search(condition, options.callback);
                                } else if(scope.search){
                                    scope.search(condition, options.callback);
                                }
                            });
                        }
                    }
                };

                //產生查詢條件
                $rootScope.genConditioninfo = function(){
                    var query_condition_info = [],
                        query_conditoin;
                    if(scope.conditionList && scope.conditionList.length>0){
                        scope.conditionList.forEach(function(condition){
                            //20180927 modify by Dustdusk for M#50923: 防止沒輸入條件
                            condition.column_name = condition.column_name||'';
                            condition.query_mode = condition.query_mode||'';
                            condition.value = condition.value||'';
                            if(condition.data_type == 'SE'){
                                //起日
                                query_conditoin = {};
                                query_conditoin.column_name = condition.column_name;
                                query_conditoin.require = condition.require;
                                query_conditoin.query_mode = 4;
                                query_conditoin.merge_condition_model = 'AND';
                                // 20190521 modify by Dustdusk for M#57628: 修正報表查詢的時間起迄不被時間影響
                                query_conditoin.value = moment(condition.value_s).format('YYYY-MM-DD') + ' 00:00:00';
                                query_condition_info.push(query_conditoin);
                                //訖日
                                query_conditoin = {};
                                query_conditoin.column_name = condition.column_name;
                                query_conditoin.require = condition.require;
                                query_conditoin.query_mode = 5;
                                query_conditoin.merge_condition_model = 'AND';
                                // 20190521 modify by Dustdusk for M#57628: 修正報表查詢的時間起迄不被時間影響
                                query_conditoin.value = moment(condition.value_e).format('YYYY-MM-DD') + ' 23:59:59';
                                query_condition_info.push(query_conditoin);

                            } else if(condition.data_type == 'C'){
                                query_conditoin = {};

                                query_conditoin.column_name = condition.column_name;
                                query_conditoin.require = condition.require;
                                query_conditoin.query_mode = 0;
                                query_conditoin.merge_condition_model = 'AND';
                                condition.check_values.forEach(function(value){
                                    if(value.checked){
                                        query_conditoin.value = value.value;
                                    }
                                });
                                if(query_conditoin.value && query_conditoin.value != ''){
                                    query_condition_info.push(query_conditoin);
                                }
                            } else if(condition.column_name != '' && condition.query_mode != '' && condition.value && condition.value != ''){
                                query_conditoin = {};
                                query_conditoin.column_name = condition.column_name;
                                query_conditoin.require = condition.require;
                                query_conditoin.query_mode = condition.query_mode;
                                query_conditoin.merge_condition_model = 'AND';

                                if(condition.data_type == 'D'){
                                    query_conditoin.value = moment(condition.value).format('YYYY-MM-DD');
                                } else {
                                    //20190125 modify by Dustdusk for M#: 查詢條件為包含時自動增加前後%
                                    if(condition.data_type!='N' && (query_conditoin.query_mode == '2'||query_conditoin.query_mode == '3')){
                                        query_conditoin.value = '%'+condition.value+'%';
                                    } else {
                                        query_conditoin.value = condition.value;
                                    }

                                }
                                query_condition_info.push(query_conditoin);
                            }
                        });
                    }
                    return query_condition_info;
                };
            }
        };
    }]);
});
